// pages/chatlist/chatlist.js
import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    chatList: [] // 聊天列表，包含每个房间的信息
  },

  onShow() {
    if (wx.getStorageSync('user')._id == undefined) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      Toast('请先登录');
    } else {
      const type = wx.getStorageSync('user').usertype
      // console.log("type",type);

      if (type != "admin") {
        this.loadChatList(); // 加载聊天列表数据

      } else {
        this.adminLoadChatList()
      }
    }
  },

  // 模拟加载聊天列表数据
  loadChatList() {
    wx.request({
      method: "POST",
      data: {
        userId: wx.getStorageSync('user')._id,
      },
      url: 'http://localhost:3000/api/allchat',
      success: (res) => {
        console.log(res.data.list);
        this.setData({
          chatList: res.data.list
        })
      }
    })
  },

  // 管理员获取所有列表
  adminLoadChatList() {
    wx.request({
      method: "GET",
      url: 'http://localhost:3000/api/allchat',
      success: (res) => {
        console.log(res.data.list);
        this.setData({
          chatList: res.data.list
        })
      }
    })
  },

  // 点击进入聊天室
  goToChatRoom(event) {
    const roomId = event.currentTarget.dataset.roomId;
    wx.navigateTo({
      url: `/pages/chatroom/chatroom?roomId=${roomId}` // 跳转到聊天页面
    });
  }
});